<?php

namespace app\admin\controller;

use  app\common\controller\Admin;

class Chapter extends Admin
{
    public function _initialize()
    {
        parent::_initialize();
        $this->setMenu();
        $this->model_id = $model_id = $this->request->param('model_id') ? $this->request->param('model_id') : 2;
        $list = db('Model')->column('*', 'id');

        if (empty($list[$model_id])) {
            return $this->error("无此模型！");
        } else {
            $this->modelInfo = $list[$model_id];
            $this->model = M($this->modelInfo['name']);
        }

        $this->assign('model_id', $model_id);
        $this->assign('model_list', $list);

    }

    /**
     * 章节列表
     * @return [html] [章节内容]
     * @author netlife <40150501@qq.com>
     */
    public function index($id)
    {
        if (!$id) {
            return $this->error("非法操作！");
        }
        $info = $this->model->find($id);

        if (!$info) {
            return $this->error($this->model->getError());
        }
        $info['model_id'] = $this->modelInfo['id'];

        //建议本章生成推广文案
        $suggestid = $info['suggestid'] ? $info['suggestid'] : config('suggestid');

        /***默认强关章节****/
        $uid = session('user_auth.uid');
        $focus = db('chapter_focus')->where(array('uid' => $uid, 'articleid' => $id))->value('focuschapter');
        $focuschapter = $focus ? $focus : ($info['focuschapter'] ? $info['focuschapter'] : config('agent_guanzhu'));
        //获取授权用户组
        $access = config('cartoon_access');
        //获取当前用户组
        $group = session('user_auth.group');

        /***章节列表***/
        $chapterlist = db('chapter')->where(array('articleid' => $id))->field('id,chaptername,chapterorder,chaptertype,size,isvip,saleprice')->order('chapterorder ASC')->paginate(config('list_rows'));

        $item = $chapterlist->items();
        $data = array(
            'articleid' => $id,
            'page' => input('page') ? input('page') : 1,
            'info' => $info,
            'focuschapter' => $focuschapter,
            'suggestid' => $suggestid,
            'chapterlist' => $chapterlist,
            'group' => $group,
            'access' => $access,
            'items' => $item,
        );
        $this->assign($data);
        $this->setMeta("[" . $info['title'] . "]" . $this->modelInfo['title'] . "章节列表");
        return $this->fetch();

    }

    public function edit($id)
    {
        $articleid = $this->request->param('articleid');
        $novelinfo = db('novel')->where("id", $articleid)->find();
        $info = db('chapter')->where('id=' . $id)->find();
        if (IS_POST) {
            //字数
            $this->param['size'] = get_count_content($this->param['content']);
            $beforesize = $info['size'];
            $chaptersize = $this->param['size'];
            //是否有金币
            if ($this->param['isvip'] && $this->param['size']) {
                $this->param['saleprice'] = round($this->param['size'] / 1000 * config('wordsperegold'));
            }


            //数据分表开启的时候
            if (config('partition')) {
                $rule = [
                    'type' => 'mod', // 分表方式
                    'num' => 10     // 分表数量
                ];
                db('novel_content')->partition(['chapterid' => $id], "chapterid", $rule)->where('chapterid=' . $id)->cache('chaptercontent' . $id)->setField('content', $this->param['content']);
            } else {
                $content = db('novel_content')->where('chapterid=' . $id)->find();
                if ($content) {
                    db('novel_content')->where('chapterid=' . $id)->cache('chaptercontent' . $id)->setField('content', $this->param['content']);
                } else {
                    $ocontent['chapterid'] = $id;
                    $ocontent['content'] = $this->param['content'];
                    db("novel_content")->insert($ocontent);
                }

            }

            unset($this->param['content']);

            //$result = $this->model->save($this->param, array('id'=> $id));
            $result = db('chapter')->where('id', $id)->cache('chapterinfo' . $id)->update($this->param);
            if ($result !== false) {
                //记录行为
                action_log('update_chapter', 'chapter', $id, session('user_auth.uid'), $info);

                $subdaysize = 0;
                $subweeksize = 0;
                $submonthsize = 0;
                $subsize = 0;
                $tmpvar = explode("-", date("Y-m-d"));
                $daystart = mktime(0, 0, 0, (int)$tmpvar[1], (int)$tmpvar[2], (int)$tmpvar[0]);
                $monthstart = mktime(0, 0, 0, (int)$tmpvar[1], 1, (int)$tmpvar[0]);
                $tmpvar = date("w");
                if ($tmpvar == 0) {
                    $tmpvar = 7;
                }

                $weekstart = $daystart;

                if (1 < $tmpvar) {
                    $weekstart -= ($tmpvar - 1) * 86400;
                }

                $clastupdate = intval($info["update_time"]);

                if ($daystart <= $clastupdate) {
                    $subdaysize += $beforesize - $chaptersize;
                }

                if ($weekstart <= $clastupdate) {
                    $subweeksize += $beforesize - $chaptersize;
                }

                if ($monthstart <= $clastupdate) {
                    $submonthsize += $beforesize - $chaptersize;
                }
                $subsize += $beforesize - $chaptersize;
                //$newdaysize = ($subdaysize < intval($article->getVar("daysize", "n")) ? intval($article->getVar("daysize", "n")) - $subdaysize : 0);
                //$newweeksize = ($subweeksize < intval($article->getVar("weeksize", "n")) ? intval($article->getVar("weeksize", "n")) - $subweeksize : 0);
                $newmonthsize = ($submonthsize < intval($novelinfo["monthsize"]) ? intval($novelinfo["monthsize"]) - $submonthsize : 0);

                $newsize = ($subsize < intval($novelinfo["size"]) ? intval($novelinfo["size"]) - $subsize : 0);
                //更新小说总字数
                if ($info["size"] != $this->param['size']) {

                    db('novel')->where(array('id' => $articleid))->update(array('monthsize' => $newmonthsize, 'size' => $newsize));
                }

                return $this->success("更新成功！", url('admin/chapter/index', array('model_id' => 1, 'id' => $articleid)));
            } else {
                return $this->error($this->model->getError(), url('admin/chapter/edit', array('model_id' => 1, 'id' => $articleid)));
            }
        } else {
            if (!$id) {
                return $this->error("非法操作！");
            }
            $info = $this->model->find($id);
            //数据分表开启的时候
            if (config('partition')) {
                $rule = [
                    'type' => 'mod', // 分表方式
                    'num' => 10     // 分表数量
                ];
                $content = db('novel_content')->partition(['chapterid' => $id], "chapterid", $rule)->where('chapterid=' . $id)->value('content');
            } else {
                $content = db('novel_content')->where('chapterid=' . $id)->value('content');
            }
            $content = html_entity_decode($content);
            if (!$info) {
                return $this->error($this->model->getError());
            }
            $info['model_id'] = $this->modelInfo['id'];
            $data = array(
                'articleid' => $articleid,
                'info' => $info,
                'content' => $content,
                'fieldGroup' => $this->getField($this->modelInfo),
            );
            $this->assign($data);
            $this->setMeta("编辑" . $this->modelInfo['title']);
            return $this->fetch();
        }
    }

    protected function getField()
    {
        $field_group = parse_config_attr($this->modelInfo['attribute_group']);

        $map['model_id'] = $this->modelInfo['id'];
        if ($this->request->action() == 'add') {
            $map['is_show'] = array('in', array('1', '2'));
        } elseif ($this->request->action() == 'edit') {
            $map['is_show'] = array('in', array('1', '3'));
        }

        //获得数组的第一条数组
        $rows = model('Attribute')->getFieldlist($map, 'id');
        if (!empty($rows)) {
            foreach ($rows as $key => $value) {
                $list[$value['group_id']][] = $value;
            }
            foreach ($field_group as $key => $value) {
                $fields[$value] = isset($list[$key]) ? $list[$key] : array();
            }
        } else {
            $fields = array();
        }
        return $fields;
    }

    public function del() {
        $id = $this->getArrayParam('id');
        $articleid = $this->getArrayParam('articleid');

        if (empty($id)) {
            return $this->error("非法操作！");
        }


        $map['id'] = array('IN', $id);

        //删除字数
        $chapter= db('chapter')->where($map)->select();


        $size = 0;
        if($chapter){
            foreach ($chapter as $k=>$v){
                if(in_array($v["status"],array(1,2))){
                    $size +=$v["size"];
                }
            }
        }
        //更新小说总字数
        if($size){
            db('novel')->where(array('id'=>$articleid[0]))->update(array('size'=>array('exp', '`size`-'.$size)));
        }

        $result = $this->model->where($map)->delete();

        if (false !== $result) {
            //记录行为
            //action_log('delete_chapter', 'chapter', $result, session('user_auth.uid'));
            foreach ($id as $ko=>$vo){
                action_log('delete_chapter','chapter',$vo,session('user_auth.uid'),$chapter[$ko]);
            }
            return $this->success("删除成功！");
        } else {
            return $this->error("删除失败！");
        }
    }
}